<?php
/*
 * Copyright 2010 Johannes M. Schmitt
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

class GoogleClosureTemplateCompiler extends JavaCompiler
{
	protected $templateCode;
	protected $compiledCode;
	
	public function __construct($templateCode) 
	{
		$this->templateCode = $templateCode;
		
		parent::__construct();
	}
	
	protected function setup() 
	{
		$this->addCommandLineFlag('inputPrefix');
		$this->addCommandLineFlag('locales');
		$this->addCommandLineFlag('messageFilePathFormat');
		$this->addCommandLineFlag('outputPathFormat');
		$this->addCommandLineFlag('shouldProvideRequireSoyNamespaces');
		$this->addCommandLineFlag('codeStyle');
		$this->addCommandLineFlag('compileTimeGlobalsFile');
		$this->addCommandLineFlag('cssHandlingScheme');
		
		$this->setCommandLineFlag('shouldProvideRequireSoyNamespaces');
		$this->setCommandLineFlag('cssHandlingScheme', 'goog');
		$this->setCommandLineFlag('codeStyle', 'STRINGBUILDER');
	}
	
	public function getJarPath() 
	{
		return dirname(__FILE__).'/../../data/closure_template_compiler/SoyToJsSrcCompiler.jar';
	}
	
	public function execute()
	{
//		$tmpDir = sfConfig::get('sf_cache_dir');
		$tmpDir = sys_get_temp_dir();
		
		$inputFile = tempnam($tmpDir, 'cin');
		file_put_contents($inputFile, $this->templateCode);
		$this->addArgument($inputFile);
		
		$outputFile = tempnam($tmpDir, 'cout');
		$this->setCommandLineFlag('outputPathFormat', $outputFile);
		
		parent::execute();
		
		$this->compiledCode = file_get_contents($outputFile);
		
		unlink($inputFile);
		unlink($outputFile);
	}
	
	public function getCompiledCode()
	{
		$this->execute();
		return ($this->error != ''? "/*\nCommand:\n".$this->getCommand()."\n\nInput:\n".$this->templateCode."\n\nError:\n".$this->error."\n*/\n" : '').$this->compiledCode;
	}
}